package org.liu.async.kit;

import net.sf.cglib.proxy.LazyLoader;
import org.liu.async.exceptions.AsyncTimeoutException;
import org.liu.async.transom.TemporaryData;

import java.util.concurrent.TimeoutException;

/**
 * Created by liuj on 2015/12/13.
 */
public class AsyncReturnObject implements LazyLoader {

    /**
     * 返回对象的future
     */
    private ObjectFuture objectFuture;

    public AsyncReturnObject(ObjectFuture objectFuture) {
        this.objectFuture = objectFuture;
    }

    /**
     * 实现lazyload方法,达到对象使用时才延迟加载
     * @return
     * @throws Exception
     */
    @Override
    public Object loadObject() throws Exception {
        try {
            Object obj = objectFuture.get();
            if (obj instanceof TemporaryData) {
                if (((TemporaryData) obj).getException() != null) {
                    throw ((TemporaryData) obj).getException();
                }
                return ((TemporaryData) obj).getOriginResult();
            }
            return obj;
        }catch (TimeoutException e){
            throw new AsyncTimeoutException("loadObject timeout",e);
        }
    }

}
